﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Enter.Admin.Utils
{
    public class FormatProvider : IFormatProvider, ICustomFormatter
    {
        private string _format;
        public FormatProvider(string format) 
        {
            _format = format;
        }

        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            if (!string.IsNullOrWhiteSpace(format)) 
            {
                _format = format;
            }
            if (arg == null) throw new ArgumentNullException("arg");
            var t = arg.GetType();
            var o_val = string.Empty;
            if (t.IsEnum)
            {
                o_val = Convert.ToString(arg);
                if (o_val == "0")
                {
                    // 处理枚举不是从0开始;
                    o_val = "";
                }
            }
            else
            {
                switch (Type.GetTypeCode(t))
                {
                    case TypeCode.DateTime:
                        
                        if (string.IsNullOrWhiteSpace(_format))
                        {
                            _format = "yyyy-MM-dd HH:mm:ss";
                        }
                        // 转换
                        {
                            DateTime data = (DateTime)arg;
                            o_val = data.ToString(_format);
                        }
                        break;
                    case TypeCode.Boolean:
                        if (string.IsNullOrWhiteSpace(_format))
                        {
                            _format = "是:否";
                        }
                        var tfs = _format.Split(":");
                        // 转换
                        {
                            bool data = (bool)arg;
                            if (data)
                            {
                                o_val = tfs[0];
                            }
                            else
                            {
                                o_val = tfs[1];
                            }
                        }
                        break;
                    default:
                        o_val = Convert.ToString(arg);
                        break;
                }
            }
            return o_val;
        }

        public object GetFormat(Type formatType)
        {
            return this;
            //if (formatType == typeof(ICustomFormatter))
            //    return this;
            //else
            //    return null;
        }
    }
}
